package com.fuint.common.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuint.common.enums.StatusEnum;
import com.fuint.common.enums.YesOrNoEnum;
import com.fuint.common.service.AddressService;
import com.fuint.framework.exception.BusinessCheckException;
import com.fuint.repository.mapper.MtAddressMapper;
import com.fuint.repository.model.MtAddress;
import com.fuint.utils.StringUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * 收货地址业务实现类
 */
@Service
@AllArgsConstructor
public class AddressServiceImpl extends ServiceImpl<MtAddressMapper, MtAddress> implements AddressService{

    private MtAddressMapper mtAddressMapper;

    /**
     * 保存收货地址
     * @param mtAddress
     * @return
     * @throws BusinessCheckException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)//这个方法是事务
    public MtAddress saveAddress(MtAddress mtAddress) throws BusinessCheckException {

        //如果传递的id>0，则更新地址。否则正常保存
        if (mtAddress.getId()>0){
            //先查到之前的地址
            MtAddress address = mtAddressMapper.selectById(mtAddress.getId());
            //将修改后的属性填入
            if (StringUtil.isNotEmpty(mtAddress.getName())){
                address.setName(mtAddress.getName());
            }
            if (StringUtil.isNotEmpty(mtAddress.getMobile())){
                address.setMobile(mtAddress.getMobile());
            }
            if (StringUtil.isNotEmpty(mtAddress.getDetail())){
                address.setDetail(mtAddress.getDetail());
            }
            if (StringUtil.isNotEmpty(mtAddress.getIsDefault())){
                //数据库里面default字段存的是string：Y|N
                if (mtAddress.getIsDefault().equals(YesOrNoEnum.YES.getKey())){
                    //如果修改此地址为默认地址
                    //需要将数据库里之前的默认地址设置为N,再更新
                    mtAddressMapper.setDefault(mtAddress.getUserId(),mtAddress.getId());
                }
                address.setIsDefault(mtAddress.getIsDefault());
            }
            if (StringUtil.isNotEmpty(mtAddress.getStatus())){
                address.setStatus(mtAddress.getStatus());
            }
            if (mtAddress.getProvinceId()>0){
                address.setProvinceId(mtAddress.getProvinceId());
            }
            if (mtAddress.getCityId()>0){
                address.setCityId(mtAddress.getCityId());
            }
            if (mtAddress.getRegionId()>0){
                address.setRegionId(mtAddress.getRegionId());
            }
            //最后，将更新内容存入数据库
            mtAddressMapper.updateById(address);
        }else{
            //新增地址
            mtAddress.setCreateTime(new Date());
            mtAddress.setUpdateTime(new Date());
            //新增地址默认设为默认地址
            mtAddress.setIsDefault(YesOrNoEnum.YES.getKey());

            this.save(mtAddress);
            //新增地址后，将之前的默认地址都清掉
            mtAddressMapper.setDefault(mtAddress.getUserId(),mtAddress.getId());

        }

        return mtAddress;
    }

    /**
     * 根据ID获取收货地址
     *
     * @param  id 地址ID
     * @throws BusinessCheckException
     * @return
     */
    @Override
    public MtAddress detail(Integer id) {
        return mtAddressMapper.selectById(id);
    }

    /**
     * 根据条件查询地址列表
     * @param params 查询参数
     * @return
     * @throws BusinessCheckException
     */
    @Override
    public List<MtAddress> queryListByParams(Map<String, Object> params) throws BusinessCheckException {
        Map<String, Object> param=new HashMap<>();
        //根据3个条件（可选）来查询列表。1.用户ID，2.状态，3.是否默认

        String status=params.get("status")==null? StatusEnum.ENABLED.getKey():params.get("status").toString();
        param.put("status",status);

        if (params.containsKey("userId")){
            param.put("user_id",params.get("userId"));
        }

        if (params.containsKey("isDefault")){
            param.put("is_default",YesOrNoEnum.YES.getKey());
        }


        return mtAddressMapper.selectByMap(param);
    }
}
